<template>
  <el-dialog
    :title="editId ? '编辑菜单' : '新增菜单'"
    v-model="dialogVisible"
    width="60%"
    :before-close="handleClose"
  >
    <el-form
      :model="goodsForm"
      :rules="rules"
      ref="goods-Form"
      label-width="120px"
    >
      <el-form-item label="商品名称" prop="goodsname">
        <el-input
          v-model="goodsForm.goodsname"
          placeholder="请输入商品名称"
          auto-complete="off"
        />
      </el-form-item>
      <el-form-item label="商品单价" prop="price">
        <el-input
          v-model="goodsForm.price"
          placeholder="请输入商品单价"
          auto-complete="off"
        />
      </el-form-item>
      <el-form-item label="市场售价" prop="market_price">
        <el-input
          v-model="goodsForm.market_price"
          placeholder="请输入市场售价"
          auto-complete="off"
        />
      </el-form-item>
      <el-form-item label="一级分类" prop="first_cateid">
        <el-select v-model="goodsForm.first_cateid">
          <el-option
            v-for="cate in cates.cateList"
            :key="cate.id"
            :label="cate.catename"
            :value="cate.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类" prop="first_cateid">
        <el-select v-model="goodsForm.second_cateid">
          <el-option
            v-for="cate in secondCateList"
            :key="cate.id"
            :label="cate.catename"
            :value="cate.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品规格" prop="specsid">
        <el-select v-model="goodsForm.specsid">
          <el-option
            v-for="specs in specs.allSpecsList"
            :key="specs.id"
            :label="specs.specsname"
            :value="specs.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="规格属性" prop="specsattr">
        <el-select v-model="goodsForm.specsattr" multiple>
          <el-option
            v-for="attr in specsAttrs"
            :key="attr"
            :label="attr"
            :value="attr"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品图片" prop="img">
        <el-upload
          action="#"
          list-type="picture-card"
          :auto-upload="false"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :limit="1"
          :on-exceed="limitTips"
          :on-change="changeFile"
          :file-list="fileList"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="Visible">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="是否新品" prop="isnew">
        <el-radio v-model="goodsForm.isnew" :label="1">新品</el-radio>
        <el-radio v-model="goodsForm.isnew" :label="2">非新品</el-radio>
      </el-form-item>
      <el-form-item label="是否热卖" prop="isnew">
        <el-radio v-model="goodsForm.ishot" :label="1">热卖</el-radio>
        <el-radio v-model="goodsForm.ishot" :label="2">非热卖</el-radio>
      </el-form-item>
      <el-form-item label="商品状态" prop="status">
        <el-radio v-model="goodsForm.status" :label="1">启用</el-radio>
        <el-radio v-model="goodsForm.status" :label="2">禁用</el-radio>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入商品描述"
          v-model="goodsForm.description"
        >
        </el-input>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog()">取消</el-button>
        <el-button type="primary" @click="submitGoods()"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
// 导入store
import useCateStore from "../../stores/cate";
import useSpecStore from "../../stores/specs";
import useGoodStore from "../../stores/goods";
// 定义
const cates = useCateStore();
const specs = useSpecStore();
const goods = useGoodStore();

// 定义控制弹窗显隐的变量
const dialogVisible = ref(false);

//关闭弹窗？
const handleClose = (done) => {
  ElMessageBox.confirm("确定关闭吗?", "关闭弹窗！", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      done();
      //   重置表单
      resetForm();
    })
    .catch(() => {
      // catch error
    });
};

// 关闭弹窗
const closeDialog = () => {
  resetForm();
};

// 定义表单
let goodsForm = reactive({
  first_cateid: "",
  second_cateid: "",
  goodsname: "",
  price: "",
  market_price: "",
  img: "",
  description: "",
  specsid: "",
  specsattr: "",
  isnew: 1,
  ishot: 1,
  status: 1,
});

// 表单规则
const rules = reactive({
  first_cateid: {
    required: true,
    message: "请选择一级分类",
    trigger: "blur",
  },
  second_cateid: {
    required: true,
    message: "请选择二级分类",
    trigger: "blur",
  },
  goodsname: {
    required: true,
    message: "请输入商品名称",
    trigger: "blur",
  },
  price: { required: true, message: "请输入商品单价", trigger: "blur" },
  market_price: {
    required: true,
    message: "请输入市场售价",
    trigger: "blur",
  },
  img: { required: true, message: "请选择商品图片", trigger: "blur" },
  description: {
    required: true,
    message: "请输入商品描述",
    trigger: "blur",
  },
  specsid: { required: true, message: "请选择商品规格", trigger: "blur" },
  specsattr: {
    required: true,
    message: "请选择商品规格属性",
    trigger: "blur",
  },
  isnew: { required: true, message: "请选择是否新品", trigger: "blur" },
  ishot: { required: true, message: "请选择是否热卖", trigger: "blur" },
  status: { required: true, message: "请选择商品状态", trigger: "blur" },
});

// 定义编辑id
let editId = ref("");

// 清空表单，关闭弹窗
const resetForm = () => {
  // 重置编辑id
  editId = ref("");
  // 初始化表单
  goodsForm = reactive({
    first_cateid: "",
    second_cateid: "",
    goodsname: "",
    price: "",
    market_price: "",
    img: "",
    description: "",
    specsid: "",
    specsattr: "",
    isnew: 1,
    ishot: 1,
    status: 1,
  });
  //   重置文件列表
  fileList = reactive([]);

  // 关闭弹窗
  dialogVisible.value = false;
};
// 获取数据
onMounted(() => {
  // 调用函数,获取分类数据
  cates.getCateListActions();
  specs.getSpecsListAction();
});

// 计算属性
const secondCateList = computed(() => {
  // 查询用户选择的一级分类索引的索引
  let index = cates.cateList.findIndex(
    (cate) => cate.id === goodsForm.first_cateid
  );
  // 将一级分类对应的二级分类获取出来：如果不存在返回空数组
  return cates.cateList[index]?.children || [];
});
const specsAttrs = computed(() => {
  // 查询用户选择商品 规格的索引
  let index = specs.allSpecsList.findIndex((sp) => sp.id === goodsForm.specsid);
  // 返回属性数组
  return specs.allSpecsList[index]?.attrs || [];
});

// 图片路径
const dialogImageUrl = ref("");
// 预览图窗口可视
const Visible = ref(false);
// 上传的文件列表
var fileList = reactive([]);
// 手动移除文件
const handleRemove = (file, fileList) => {
  console.log(file, fileList);
};
// 图片预览函数;
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  Visible.value = true;
};
// 下载图片
const handleDownload = (file) => {
  console.log(file);
};
// 文件超出限制数量的提示
const limitTips = () => {
  ElMessage({
    type: "warning",
    message: "你只能选择一张图片作为封面",
  });
};
const changeFile = (file) => {
  //   console.log("修改了文件", file);
  //   设置表单封面图
  goodsForm.img = file.raw;
};

// 提交
const submitGoods = () => {
  console.log(" goodsForm ", goodsForm);
  console.log("editId", editId);
  if (editId.value) {
    goods.editGoodsActions({ ...goodsForm, id: editId.value });
  } else {
    goods.addGoodsAction(goodsForm);
  }
  resetForm();
};

// 接收父组件数据
const acceptValue = (value) => {
  //   console.log("value", value);
  editId.value = value.id;
  //   直接解构多出两个属性
  //   goodsForm = reactive({ ...value });
  let goodsObj = { ...value };
  delete goodsObj.firstcatename;
  delete goodsObj.secondcatename;
  //   console.log("goodsObj", goodsObj);
  goodsForm = reactive(goodsObj);
  fileList.push({
    url: "http://localhost:3000" + value.img,
  });
  //   属性数组赋值
  goodsForm.specsattr = value.specsattr.split(",");
};

// 将变量与函数暴露出来,此代码片段放到下面
defineExpose({
  dialogVisible,
  acceptValue,
});
</script>

<style lang="css" scoped></style>
